package com.zbkj.common.core;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.img.Img;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.sts20150401.models.AssumeRoleResponse;
import com.aliyun.tea.TeaException;
import com.tiangong.framework.bo.CDO;
import com.tiangong.framework.bo.Return;
import com.zbkj.common.utils.SpringUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.UUID;

@Configuration
public class OSSUtils {

    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId;
    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret;
    @Value("${aliyun.oss.domain}")
    private String domain;
    @Value("${aliyun.oss.bucket}")
    private String bucket;
    @Value("${aliyun.oss.endpoint}")
    private String endpoint;

    @Value("${aliyun.oss.sts.endpoint}")
    private String sts_endpoint;
    @Value("${aliyun.oss.sts.rolearn}")
    private String sts_rolearn;
    @Value("${aliyun.oss.sts.roleSessionName}")
    private String sts_roleSessionName;
    @Value("${aliyun.oss.sts.durationSeconds}")
    private Long sts_durationSeconds;
    @Value("${aliyun.oss.sts.policy}")
    private String sts_policys;





//    private   String accessKeyId="LTAIgR7VCPXqYg3r";
//    private   String accessKeySecret="XS1g6hLzlQAX2cmm9imQumsfU2NP0S";
//    private   String domain="https://loansmanage.oss-cn-beijing.aliyuncs.com";
//    private   String bucket="loansmanage";
//    private   String endpoint = "https://oss-cn-beijing.aliyuncs.com";


    public static OSSUtils getInstance() {
        OSSUtils bean = SpringUtil.getBean(OSSUtils.class);
        return bean;
    }

    public Return upload(MultipartFile mfile, Boolean compress) {


        long size = mfile.getSize() / 1024;
        if (size <= 300) {
            compress = false;
        }
//        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

//        MultipartFile mfile = multipartRequest.getFile("file");// 获取上传文件对象

        String contentType1 = mfile.getContentType();
        String[] fileInfo = mfile.getOriginalFilename().split("\\.");
        String fileFormat = fileInfo[fileInfo.length - 1];
        String fileSourceName = fileInfo[fileInfo.length - 2];
        String name = UUID.randomUUID() + RandomStringUtils.random(4, false, true);
        String fileName = name + "." + fileFormat;

        InputStream fileInputStream_old = null;
        try {
            fileInputStream_old = mfile.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //WARN
        //   FileUtil.re


        //InputStream fileInputStream = null;
        File newFile = new File(fileName);
        try {
            if (compress != null && compress) {
                fileName = name + ".jpg";
                Img.from(fileInputStream_old).setQuality(0.3).write(newFile);
                //  fileInputStream=new FileInputStream(newFile);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ObjectMetadata metadata = new ObjectMetadata();
        long length = newFile.length();
        //上传的文件的长度
        try {
            metadata.setContentLength(newFile.length() == 0 ? fileInputStream_old.available() : newFile.length());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //指定该Object被下载时的网页的缓存行为
        metadata.setCacheControl("no-cache");
        //指定该Object下设置Header
        metadata.setHeader("Pragma", "no-cache");
        //指定该Object被下载时的内容编码格式
        metadata.setContentEncoding("utf-8");
        //文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
        //如果没有扩展名则填默认值application/octet-stream
        String contentType = getContentType(fileName);
        if (StringUtils.isNotBlank(contentType)) {
            metadata.setContentType(contentType);
        }
        //指定该Object被下载时的名称（指示MINME用户代理如何显示附加的文件，打开或下载，及文件名称）
        metadata.setContentDisposition("filename/filesize=" + fileName + "/" + "Byte.");

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String dirName = "img" + "/" + System.currentTimeMillis();

        if (contentType.contains("image")) {
            dirName = "static/image/" + DateUtil.format(DateUtil.date(), "yyyyMMdd");
        } else {
            dirName = "static/files/" + DateUtil.format(DateUtil.date(), "yyyyMMdd");
        }

        try {
            if (newFile.length() != 0) {
                PutObjectResult putObjectResult = ossClient.putObject(bucket, dirName + "/" + fileName, newFile, metadata);
                size = newFile.length() / 1024;
            } else {
                PutObjectResult putObjectResult = ossClient.putObject(bucket, dirName + "/" + fileName, fileInputStream_old, metadata);
            }
        } catch (Exception oe) {
            oe.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        String url = "https://"+domain + "/" + dirName + "/" + fileName;
        System.out.println(url);
        CDO cdoResult = new CDO();
        cdoResult.set("url", url);
        cdoResult.set("filesize", size);
        cdoResult.set("compress", newFile.length() != 0 ? true : false);
        if (newFile.exists()) {
            newFile.delete();
        }
        return Return.valueOf(cdoResult);
    }


    public com.aliyun.sts20150401.Client createClient() {
        // 工程代码泄露可能会导致 AccessKey 泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考。
        // 建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378657.html。
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config()
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
                .setAccessKeyId(accessKeyId)
                // 必填，请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
                .setAccessKeySecret(accessKeySecret);
        // Endpoint 请参考 https://api.aliyun.com/product/Sts
        config.endpoint = sts_endpoint;
        try {
            return new com.aliyun.sts20150401.Client(config);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public Return getSTS() {
        com.aliyun.sts20150401.Client client = createClient();
        com.aliyun.sts20150401.models.AssumeRoleRequest assumeRoleRequest = new com.aliyun.sts20150401.models.AssumeRoleRequest()
                .setDurationSeconds(sts_durationSeconds)
                .setPolicy(sts_policys)
                .setRoleArn(sts_rolearn)
                .setRoleSessionName(sts_roleSessionName);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            AssumeRoleResponse assumeRoleResponse = client.assumeRoleWithOptions(assumeRoleRequest, runtime);
            System.out.println(JSONObject.toJSONString(assumeRoleResponse));
            CDO cdoResult = CDO.parseObject(assumeRoleResponse);
            cdoResult.set("domain","https://"+domain);
            cdoResult.set("bucketName",bucket);
            cdoResult.set("endpoint","https://"+endpoint);
            return Return.valueOf(cdoResult);
        } catch (TeaException error) {
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 此处仅做打印展示，请谨慎对待异常处理，在工程项目中切勿直接忽略异常。
            // 错误 message
            System.out.println(error.getMessage());
            // 诊断地址
            System.out.println(error.getData().get("Recommend"));
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        return Return.EXCEPTION;
    }

    /**
     * 通过文件名判断并获取OSS服务文件上传时文件的contentType
     *
     * @param fileName 文件名
     * @return 文件的contentType
     */
    public static String getContentType(String fileName) {
        //文件的后缀名
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        if (".bmp".equalsIgnoreCase(fileExtension)) {
            return "image/bmp";
        }
        if (".gif".equalsIgnoreCase(fileExtension)) {
            return "image/gif";
        }
        if (".jpeg".equalsIgnoreCase(fileExtension)
                || ".jpg".equalsIgnoreCase(fileExtension) ||
                ".png".equalsIgnoreCase(fileExtension)) {
            return "image/jpeg";
        }
        if (".html".equalsIgnoreCase(fileExtension)) {
            return "text/html";
        }
        if (".txt".equalsIgnoreCase(fileExtension)) {
            return "text/plain";
        }
        if (".vsd".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.visio";
        }
        if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
            return "application/msword";
        }
        if (".xml".equalsIgnoreCase(fileExtension)) {
            return "text/xml";
        }
        if (".flv".equalsIgnoreCase(fileExtension)) {
            return "video/x-flv";
        }
        if (".mp3".equalsIgnoreCase(fileExtension)) {
            return "audio/mpeg";
        }
        if (".mp4".equalsIgnoreCase(fileExtension)) {
            return "video/mp4";
        }
        //默认返回类型
        return "";
    }

    public static void main(String[] args) throws Exception {
//        System.out.println(DateUtil.format(DateUtil.date(), "{\"Statement\":[{\"Action\":\"oss:*\",\"Effect\":\"Allow\",\"Resource\":\"acs:oss:*:*:*\"}],\"Version\":\"1\"}"));
        new OSSUtils().upload("https://www.52zcw.com/wp-content/uploads/2024/05/1715179464-980f9daadb6f708.jpg",false);
    }


    public Return upload(String weburl, Boolean compress) {

        InputStream inputStream = null;
        try {
            inputStream = new URL(weburl).openStream();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String fileFormat = weburl.split("\\.")[weburl.split("\\.").length-1];

        String name = UUID.randomUUID() + RandomStringUtils.random(4, false, true);
        String fileName = name + "." + fileFormat;

        InputStream fileInputStream_old = null;
        try {
            fileInputStream_old = inputStream;
        } catch (Exception e) {
            e.printStackTrace();
        }
        //WARN
        //   FileUtil.re


        //InputStream fileInputStream = null;
        File newFile = new File(fileName);
        try {
            if (compress != null && compress) {
                fileName = name + ".jpg";
                Img.from(fileInputStream_old).setQuality(0.3).write(newFile);
                //  fileInputStream=new FileInputStream(newFile);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ObjectMetadata metadata = new ObjectMetadata();
        long length = newFile.length();
        //上传的文件的长度
        try {
            metadata.setContentLength(newFile.length() == 0 ? fileInputStream_old.available() : newFile.length());
        } catch (Exception e) {
            e.printStackTrace();
        }
        //指定该Object被下载时的网页的缓存行为
        metadata.setCacheControl("no-cache");
        //指定该Object下设置Header
        metadata.setHeader("Pragma", "no-cache");
        //指定该Object被下载时的内容编码格式
        metadata.setContentEncoding("utf-8");
        //文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
        //如果没有扩展名则填默认值application/octet-stream
        String contentType = getContentType(fileName);
        if (StringUtils.isNotBlank(contentType)) {
            metadata.setContentType(contentType);
        }
        //指定该Object被下载时的名称（指示MINME用户代理如何显示附加的文件，打开或下载，及文件名称）
        metadata.setContentDisposition("filename/filesize=" + fileName + "/" + "Byte.");

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String dirName = "img" + "/" + System.currentTimeMillis();

        if (contentType.contains("image")) {
            dirName = "static/image/" + DateUtil.format(DateUtil.date(), "yyyyMMdd");
        } else {
            dirName = "static/files/" + DateUtil.format(DateUtil.date(), "yyyyMMdd");
        }

        try {
            if (newFile.length() != 0) {
                PutObjectResult putObjectResult = ossClient.putObject(bucket, dirName + "/" + fileName, newFile, metadata);
//                size = newFile.length() / 1024;
            } else {
                PutObjectResult putObjectResult = ossClient.putObject(bucket, dirName + "/" + fileName, fileInputStream_old, metadata);
            }
        } catch (Exception oe) {
            oe.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        String url = "https://"+domain + "/" + dirName + "/" + fileName;
        System.out.println(url);
        CDO cdoResult = new CDO();
        cdoResult.set("url", url);
//        cdoResult.set("filesize", size);
        cdoResult.set("compress", newFile.length() != 0 ? true : false);
        if (newFile.exists()) {
            newFile.delete();
        }
        return Return.valueOf(cdoResult);
    }
}
